package com.southwind.phone_store_demohd.controller;


import com.southwind.phone_store_demohd.exception.PhoneException;
import com.southwind.phone_store_demohd.form.AddressForm;
import com.southwind.phone_store_demohd.service.AddressService;
import com.southwind.phone_store_demohd.util.ResultVOUtil;
import com.southwind.phone_store_demohd.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/address")
@Slf4j
public class AddressHandler {

    @Autowired
    private AddressService addressService;

    //显示全部的地址
    @GetMapping("/list")
    public ResultVO list(){
        return ResultVOUtil.success(addressService.findAll());
    }


//新增地址
    @PostMapping("/create")
    //这里把用户传递过来的数据进行了form包封装（@Valid 进行一个验证，用@RequestBody这个注解把前端的json对象转换成java对象）
    //新增错误的话，会把数据传递给BindingResult这个对象
    public ResultVO create(@Valid @RequestBody AddressForm addressForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【添加地址】参数错误,addressForm={}",addressForm);//抛出异常
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());//把错误信息显示出来
        }

        //没有问题，就把新增的信息传递给数据库
        addressService.saveOrUpdate(addressForm);

        return ResultVOUtil.success(null);
    }


//修改地址
    @PutMapping("/update")
    public ResultVO update(@Valid @RequestBody AddressForm addressForm,BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【修改地址】参数错误,addressForm={}",addressForm);
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());
        }

        addressService.saveOrUpdate(addressForm);

        return ResultVOUtil.success(null);
    }
}
